#ifndef SRTSUBTITLE_H
#define SRTSUBTITLE_H

#include "Common/commontypes.h"

#include <string>
#include <vector>
#include <fstream>

class SubtitleException : public std::exception
{
public:
    SubtitleException(const std::string& message) throw()
    : m_Message(message)
    {
    }

    ~SubtitleException() throw() {}

    const char* what() const throw()
    {
        return m_Message.c_str();
    }

private:
    std::string     m_Message;
};

struct SubtitleEntity
{
    uint32      index;
    uint64      startTime;
    uint64      endTime;
    std::string line1;
    std::string line2;

    SubtitleEntity()
    : index(0)
    , startTime(0)
    , endTime(0)
    {
    }

    bool operator==(uint64 timestamp)
    {
        return (timestamp >= startTime && timestamp < endTime);
    }
};

class SrtSubtitle
{
public:
    typedef std::vector<SubtitleEntity> SubtitleList;

    SrtSubtitle();
    SrtSubtitle(const std::string& filename);
    ~SrtSubtitle();

    bool getSubtitle(uint64 timestamp, SubtitleEntity& entity);
    void open(const std::string& filename);

private:
    void readSubtitleFile(const std::string& filename, std::vector<std::string>& lines);
    void parseIndexLine(const std::string& line, SubtitleEntity& entity);
    void parseTimestampLine(const std::string& line, SubtitleEntity& entity);
    void parseFirstSubtitleLine(const std::string& line, SubtitleEntity& entity);
    void parseSecondSubtitleLine(const std::string& line, SubtitleEntity& entity);
    void throwOnEmpty(const std::string& line);

private:
    SubtitleList    m_Subtitles;
};

#endif
